package com.ruicar.afs.cloud.manage.common.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import com.ruicar.afs.cloud.image.config.FileProperties;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import com.ruicar.afs.cloud.manage.common.entity.ComAttachementFile;
import com.ruicar.afs.cloud.manage.common.mapper.ComAttachementFileMapper;
import com.ruicar.afs.cloud.manage.common.service.ComAttachementFileService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: Lee
 * @date 2020-05-30 04:45:15
 * @description
 */
@Slf4j
@AllArgsConstructor
@Service
public class ComAttachementFileServiceImpl extends ServiceImpl<ComAttachementFileMapper, ComAttachementFile> implements ComAttachementFileService {

    private final FileProperties fileProperties;
    private final ComAttachmentFileService attachmentFileService;
    private final ComAttachmentFileService comAttachmentFileService;

    @Override
    public boolean saveFile(String contractNo, String caseNo, String busiNo) {
        Boolean flag = false;
        List<ComAttachementFile> comAttachementFiles = list(Wrappers.<ComAttachementFile>query().lambda()
                .eq(ComAttachementFile::getBusiNo, busiNo)
                .eq(ComAttachementFile::getBelongNo, contractNo)
                .eq(ComAttachementFile::getCreateBy, SecurityUtils.getUser().getUsername()));
        List<ComAttachementFile> comAttachementFile = list(Wrappers.<ComAttachementFile>query().lambda()
                .eq(ComAttachementFile::getBusiNo, caseNo)
                .eq(ComAttachementFile::getBelongNo, contractNo)
                .eq(ComAttachementFile::getCreateBy, SecurityUtils.getUser().getUsername())
                .eq(ComAttachementFile::getRemake, busiNo));
        if (EmptyUtils.isEmpty(comAttachementFiles) && EmptyUtils.isEmpty(comAttachementFile)) {
            flag = true;
        }
        comAttachementFiles.forEach(file -> {
            file.setBusiNo(caseNo);
            file.setRemake(busiNo);
            updateById(file);
        });
        return flag;
    }

    @Override
    public void downloadBatchFile(HttpServletResponse response, String caseNo) {
        // 1-临时目录
        String destPath = fileProperties.getTempDir() + File.separator + caseNo + File.separator + DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.randomNumber();
        // 2-远程下载
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", comAttachmentFileService.getAuthorization());
        ComAttachmentFile attachmentFile = attachmentFileService.getOne(Wrappers.<ComAttachmentFile>query().lambda()
                .eq(ComAttachmentFile::getBusiNo, caseNo)
                .orderByDesc(ComAttachmentFile::getCreateTime), false);
        byte[] fileByte = attachmentFileService.downloadAttachmentFile(attachmentFile);
        BufferedInputStream bufferedInputStream = null;
        try {
            response.reset(); // 重点突出
            if (fileByte.length > 0) {
                bufferedInputStream = new BufferedInputStream(IoUtil.toStream(fileByte));
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;filename=" + HttpUtil.encodeUtf8(attachmentFile.getFileName()));
                IoUtil.copy(bufferedInputStream, response.getOutputStream(), 1024);
                response.getOutputStream().flush();
                IoUtil.close(bufferedInputStream);
                return;
            }
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (Exception e) {
            IoUtil.close(bufferedInputStream);
            FileUtil.del(destPath);
            log.error("文件下载失败:" + e.getMessage());
        } finally {
            IoUtil.close(bufferedInputStream);
        }
    }


}
